const {createCanvas, Image} = require('canvas')
const echarts = require('echarts')



// 生成图片
exports.generateImage = function (options, width, height, theme) {
    console.log("GENERATE IMAGE")
    console.log(`WIDTH: ${width}`)
    console.log(`HEIGHT: ${height}`)
    console.log(`THEME: ${theme}`)
    console.log(`OPTIONS: ${JSON.stringify(options)}`)
    const canvas = createCanvas(width, height)
    let chart = echarts.init(null, null, {
        renderer: 'svg', // 必须使用 SVG 模式
        ssr: true, // 开启 SSR
        width: width, // 需要指明高和宽
        height: height
    });

    chart.setOption(options);

    let svgDataURL = chart.getSvgDataURL();
    svgDataURL = decodeURIComponent(svgDataURL);
    // svgDataURL = svgDataURL.slice(33);
    // svgDataURL = `data:image/svg+xml;base64,${btoa(svgDataURL)}`;
    let image = new Image();
    image.src = svgDataURL;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(image, 0, 0);
    let dataURL = canvas.toBuffer();

    chart.dispose();
    chart = null;
    return dataURL;

}

exports.generateImageCanvas = function (options, width, height, theme) {
    console.log("GENERATE IMAGE")
    console.log(`WIDTH: ${width}`)
    console.log(`HEIGHT: ${height}`)
    console.log(`THEME: ${theme}`)
    console.log(`OPTIONS: ${JSON.stringify(options)}`)
    const canvas = createCanvas(width, height)
    // ECharts 可以直接使用 node-canvas 创建的 Canvas 实例作为容器
    let chart = echarts.init(canvas,null);
    // let chart = echarts.init(null, null, {
    //     renderer: 'svg', // 必须使用 SVG 模式
    //     ssr: true, // 开启 SSR
    //     width: width, // 需要指明高和宽
    //     height: height
    // });
    chart.setOption(options);

    let buffer = canvas.toBuffer();
    chart.dispose();
    chart = null;
    return buffer

}